package pl.streamsoft.currencyApp.parser;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import pl.streamsoft.currencyApp.model.Currency;
import pl.streamsoft.currencyApp.model.CurrencyInfo;
import pl.streamsoft.currencyApp.model.CurrencyValue;
import pl.streamsoft.currencyApp.stream.IStream;

public class XMLCurrencyParser implements ICurrencyParser {

	private final static List<Currency> emptyList = Collections.unmodifiableList(new ArrayList<Currency>());
	private final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public List<Currency> getListOfCurrencies(IStream stream) {

		InputStream is = stream.getInputStream();
		if(is == null){ return emptyList; }
		Element rootNode;
		
		try {
			rootNode = new SAXBuilder().build(is).getRootElement();
		} catch (Exception e) {
			return emptyList;
		} 
		
		final List<Currency> currencies = new ArrayList<Currency>();
		final String dateOfPublication = rootNode.getChildText("data_publikacji");

		for (Element element : rootNode.getChildren("pozycja")) {
			
			
			CurrencyValue currencyValue = new CurrencyValue();
						
			currencyValue.setAverageRate(new BigDecimal(element.getChildText("kurs_sredni").replace(',', '.')));
			
			try{ currencyValue.setDateOfPublication(dateFormatter.parse(dateOfPublication)); } catch(ParseException e){ currencyValue.setDateOfPublication(null); }
			
			CurrencyInfo currencyInfo = CurrencyInfo.getInstance(
					element.getChildText("nazwa_waluty"),
					element.getChildText("kod_waluty"),
					Integer.parseInt(element.getChildText("przelicznik")));
			
			currencies.add(new Currency(currencyInfo, currencyValue));
		}
		
		return currencies;
	}
}
